package top.frsf.reggie.filter;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;
import top.frsf.reggie.common.BaseContext;
import top.frsf.reggie.common.R;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author FRSF
 * @Date 2023/1/10 12:14
 * @Description 检查用户是否登录
 */

@Slf4j
@WebFilter(filterName = "loginFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    // Spring自带的路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 1.获取本次请求URI
        String requestURI = request.getRequestURI();

        // 不需处理的 接口+路径
        String[] urls = {
                "/backend/**",      // 后端页面
                "/front/**",        // 前端页面
                "/employee/login",  // 后端登录
                "/employee/logout", // 后端登出
                "/common/**",       // 图片上下传
                "/user/sendMsg",    // 移动端发送信息
                "/user/login",      // 移动端登录
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };

        // 2.判断本次请求是否需要处理
        if (check(requestURI, urls)) {
            filterChain.doFilter(request, response);
            return;
        }

        // 3.判断后端登录状态，如果已经登录，则直接放行
        Long empId = (Long) request.getSession().getAttribute("employee");
        if (empId != null) {
            BaseContext.setCurrentId(empId);
            filterChain.doFilter(request, response);
            return;
        }

        // 3-2.判断移动端登录状态，如果已经登录，则直接放行
        Long userId = (Long) request.getSession().getAttribute("user");
        if (userId != null) {
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request, response);
            return;
        }


        // 4.若未登录，返回未登录结果，通过输出流方式
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }

    /**
     * @param requestURI: 本次请求uri
     * @param urls:       允许放行的uris
     * @Author: FRSF
     * @Date: 2023/1/10 13:20
     * @Description 路径匹配，检查本次请求是否需要放行
     * @return: boolean   是否放行
     */
    public boolean check(String requestURI, String[] urls) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match) return true;
        }
        return false;
    }

}
